package com.YCH.article.service.impl;

import com.YCH.article.service.AppArticleInfoService;
import com.YCH.article.service.AppArticleService;
import com.YCH.common.article.constans.ArticleConstans;
import com.YCH.model.article.dtos.ArticleActionDto;
import com.YCH.model.article.dtos.ArticleHomeDto;
import com.YCH.model.article.dtos.ArticleInfoDto;
import com.YCH.model.article.pojos.TbArticle;
import com.YCH.model.article.vos.ApShowArticle;
import com.YCH.model.article.vos.ArticleActionVo;
import com.YCH.model.article.vos.ArticleShowList;
import com.YCH.model.article.vos.LocationVo;
import com.YCH.model.common.dtos.ResponseResult;
import com.YCH.model.mappers.app.TbArticleConfigMapper;
import com.YCH.model.mappers.app.TbArticleMapper;
import com.YCH.model.user.vo.UserVo;
import com.YCH.utils.threadlocal.AppThreadLocalUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.YCH.model.user.pojos.TbUser;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@SuppressWarnings("all")
public class AppArticleServiceImpl implements AppArticleService {
    // 单页最大加载的数字
    private final  static short MAX_PAGE_SIZE = 50;

    Logger logger = LoggerFactory.getLogger(AppArticleServiceImpl.class);
    @Autowired
    private TbArticleMapper tbArticleMapper;
    @Autowired
    private AppArticleInfoService appArticleInfoService;
    @Autowired
    TbArticleConfigMapper tbArticleConfigMapper;
    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type) {
        // 参数校验
        if(dto == null ){
            dto = new ArticleHomeDto();
        }
        Integer size = dto.getPageSize();
        String tag = dto.getTag();
        // 最大时间处理
        if(dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        // 最小时间处理
        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        // 分页参数校验
        if (size == null || size <= 0) {
            size = 20;
        }
        size = Math.min(size,MAX_PAGE_SIZE);
        dto.setPageSize(size);
        // 文章频道参数验证
        if (StringUtils.isEmpty(tag)) {
            dto.setTag(ArticleConstans.DEFAULT_TAG);
        }
        //  类型参数校验
        if (!type.equals(ArticleConstans.LOADTYPE_LOAD_MORE) && !type.equals(ArticleConstans.LOADTYPE_LOAD_NEW))
            type = ArticleConstans.LOADTYPE_LOAD_MORE;
        // 获取用户信息
        TbUser user = AppThreadLocalUtils.getUser();
        // 判断用户是否存在
        if(user!=null){
            // 存在 已登录 加载推荐的文章
            List<ApShowArticle> defaultArticles = getDefaultArticle(dto, type);
            return ResponseResult.okResult(defaultArticles);
        }else{ // 不存在 未登录 加载默认的文章
            List<ApShowArticle> defaultArticles = getDefaultArticle(dto, type);
            return ResponseResult.okResult(defaultArticles);
        }
    }
    /**
     * 先从用户的推荐表中查找文章，如果没有再从大文章列表中获取
     * @param user
     * @param dto
     * @param type
     * @return
     */
    // private List<TbArticle> getUserArticle(TbUser user, ArticleHomeDto dto, Short type) {
    //     List<TbUserArticleList> list = tbUserArticleListMapper.loadArticleIdListByUser(user,dto,type);
    //     if(!list.isEmpty()){
    //         return tbArticleMapper.loadArticleListByIdList(list);
    //     }else{
    //         return getDefaultArticle(dto,type);
    //     }
    // }

    /**
     * 从默认的大文章列表中获取文章
     * @param dto
     * @param type 1：更多 2：最新
     * @return
     */
    private List<ApShowArticle> getDefaultArticle(ArticleHomeDto dto, Short type){
        // 校验参数
        // 默认每页为10个
        if (dto.getPageSize() == null || dto.getPageSize() <= 0){
            dto.setPageSize(10);
        }
        // 默认第一页
        if(dto.getPageNum() == null || dto.getPageNum() <= 0){
            dto.setPageNum(1);
        }
        PageHelper.clearPage();
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        // 拿到结果集
        List<TbArticle> defaultArticles = tbArticleMapper.loadArticleListByLocation(dto,type);
        PageInfo<TbArticle> pageInfo = new PageInfo<>(defaultArticles);
        List<TbArticle> list = pageInfo.getList();
        if (list.isEmpty() || list.size() == 0){
            return null;
        }
        // 从结果集中移除isPublic为false的值
        List<TbArticle> Articles = new ArrayList<>();
        for(TbArticle tbArticle : list){
            Boolean isPublic = tbArticleConfigMapper.selectByArticleId(tbArticle.getId()).getIsPublic();
            if(isPublic){
                Articles.add(tbArticle);
            }
        }
        // 封装到vo列表
        List<ApShowArticle> apShowArticleList = new ArrayList<>();
        // 设置点赞、收藏、查看、评论数量dto
        ArticleActionDto articleActionDto = new ArticleActionDto();
        articleActionDto.setType((short) 0);
        // 将结果集封装到vo
        for (TbArticle defaultArticle:Articles) {
            ApShowArticle apShowArticle = new ApShowArticle();
            apShowArticle.setCategoryId(defaultArticle.getCategoryId());
            // 设置省市区
            LocationVo locationVo = new LocationVo();
            locationVo.setProvinceId(defaultArticle.getProvinceId());
            locationVo.setCityId(defaultArticle.getCityId());
            locationVo.setCountyId(defaultArticle.getCountyId());
            apShowArticle.setLocation(locationVo);
            // 点赞、收藏、查看、评论数量、转发、阅读位置（未实现）
            articleActionDto.setArticleId(defaultArticle.getId());
            // spring中同一个service中方法相互调用事务
            ArticleActionVo articleActionVo = (ArticleActionVo) appArticleInfoService.loadArticleAction(articleActionDto).getData();
            apShowArticle.setArticleOpeartor(articleActionVo);
            // 点赞、收藏、查看、评论数量、转发、阅读位置 配置（未实现）
            ArticleInfoDto articleInfoDto = new ArticleInfoDto();
            articleInfoDto.setArticleId(defaultArticle.getId());
            articleInfoDto.setUserId(dto.getUserId());
            articleInfoDto.setAuthorId(defaultArticle.getUser().getId());
            HashMap<String, Boolean> articleOperatorConfig = (HashMap<String, Boolean>) appArticleInfoService.loadArticleBehavior(articleInfoDto).getData();
            apShowArticle.setArticleOperatorConfig(articleOperatorConfig);
            // 时间
            apShowArticle.setCreatTime(defaultArticle.getCreatTime());
            try{
                // 文章列表内容
                ArticleShowList articleShowList = new ArticleShowList();
                articleShowList.setArticleId(defaultArticle.getId());
                articleShowList.setTitle(defaultArticle.getTitle());
                articleShowList.setImage(defaultArticle.getImage());
                // 设置内容
                articleShowList.setPartContent(defaultArticle.getPartContent());
                articleShowList.setCustomTag(defaultArticle.getTag());
                articleShowList.setTagName(defaultArticle.getFlag().getTagName());
                articleShowList.setTagId(defaultArticle.getFlag().getId());
                apShowArticle.setContent(articleShowList);
                // 设置用户性息
                UserVo userVo = new UserVo();
                userVo.setUserId((int) defaultArticle.getUser().getId());
                userVo.setUserName(defaultArticle.getUser().getUsername());
                userVo.setLV((int) defaultArticle.getLv().getLV());
                userVo.setHeadimg(defaultArticle.getUser().getHeadimg());
                userVo.setNick(defaultArticle.getUser().getNick());
                userVo.setSign(defaultArticle.getUser().getSign());
                userVo.setSex(defaultArticle.getUser().getSex());
                apShowArticle.setUser(userVo);
            }catch (NullPointerException e){
                logger.error("展示文章列表中tagId或者UserId为空" + e.getStackTrace());
                continue;
            }
            apShowArticleList.add(apShowArticle);
        }
        return apShowArticleList;
    }

    /**
     * 根据地点从获取文章
     * @param dto
     * @param type
     * @return
     */
    private List<TbArticle> getLocationArticle(ArticleHomeDto dto, Short type){
        return tbArticleMapper.loadArticleListByLocation(dto,type);
    }

}
